﻿using System;
using System.Data;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.controls;
using Commerce.Common;
using System.Reflection;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class editCoupon : umbraco.BasePages.UmbracoEnsuredPage
    {
        // TODO: Not supported in umbraco 4.5.
        //private umbraco.controls.datePicker ExpirationDate;
        private DateTime ExpirationDate;
        protected Coupon thisCoupon = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CouponType.Items.Clear();
                CouponTypeCollection coupontypes = new CouponTypeCollection().OrderByAsc("Description").Load();               
                CouponType.Items.Add(new ListItem("choose", "0"));
                foreach (CouponType thisCouponType in coupontypes)
                {
                    CouponType.Items.Add(new ListItem(thisCouponType.Description, thisCouponType.CouponTypeId.ToString()));
                }

                string couponCode = Request.QueryString.Get("c");
                Coupon thisCoupon = new Coupon("CouponCode", couponCode);

                CouponCode.Text = thisCoupon.CouponCode;
                CouponType.SelectedValue = thisCoupon.CouponTypeId.ToString();
                IsSingleUse.Checked = thisCoupon.IsSingleUse;

                if (thisCoupon.ExpirationDateHasValue)
                {
                    ExpirationDate = thisCoupon.ExpirationDate;
                    ExpirationDate1.Text = thisCoupon.ExpirationDate.ToShortDateString();
                }
                else
                {
                    ExpirationDate1.Text = DateTime.Now.AddMonths(1).ToShortDateString();
                }
             }

            this.Panel1.Text = "Edit Coupon";
            this.pp_couponcode.Text = "Coupon Code";
            this.pp_coupontype.Text = "Coupon Type";
            this.pp_issingleuse.Text = "Is Single Use";
            this.pp_expirationdate.Text = "Expiration Date";
        }

        protected List<ListItem> BindCategoryData(List<int> selected, bool includeProducts)
        {
            List<ListItem> productList = new List<ListItem>();

            // get collection values
            Commerce.Common.CategoryCollection parentcategories = null;

            parentcategories = new CategoryCollection().Where("parentID", SubSonic.Comparison.Equals, 0).OrderByAsc("categoryName").Load();

            if (parentcategories.Count > 0)
            {
                foreach (Category c in parentcategories)
                {
                    ListItem li = new ListItem();
                    li.Text = string.Format("<span class='Level0'>{0}</span>", c.CategoryName);
                    li.Value = c.CategoryID.ToString();
                    if (includeProducts == true)
                    {
                        li.Enabled = false;
                    }
                    else
                    {
                        if (selected.Exists(delegate(int i) { return i == Int32.Parse(li.Value); }) == true)
                        {
                            li.Selected = true;
                        }
                    }
                   
                    productList.Add(li);

                    RenderSubcategories(c.CategoryID, 1, productList, selected, includeProducts);
                }
            }
            
            return productList;
        }

        protected void RenderSubcategories(int parentcatid, int level, List<ListItem> productList, List<int> selected, bool includeProducts)
        {
            if (includeProducts == true)
            {
                RenderProducts(parentcatid, level, productList, selected);
            }

            // get collection values
            Commerce.Common.CategoryCollection categories = null;

            categories = new CategoryCollection().Where("parentID", SubSonic.Comparison.Equals, parentcatid).OrderByAsc("categoryName").Load();

            if (categories.Count > 0)
            {
                int lvl = level + 1;
                foreach (Category c in categories)
                {
                    ListItem li = new ListItem();
                    li.Text = string.Format("<span class='{1}'>{0}</span>", c.CategoryName, string.Format("Level{0}", level));
                    li.Value = c.CategoryID.ToString();
                    li.Attributes.Add("style", "margin-left:20px;");
                    if (includeProducts == true)
                    {
                        li.Enabled = false;
                    }
                    else
                    {
                        if (selected.Exists(delegate(int i) { return i == Int32.Parse(li.Value); }) == true)
                        {
                            li.Selected = true;
                        }
                    }

                    productList.Add(li);

                    RenderSubcategories(c.CategoryID, lvl, productList, selected, includeProducts);
                }
            }
        }

        protected void RenderProducts(int parentcatid, int level, List<ListItem> productList, List<int> selected)
        {
            // get collection values
            Commerce.Common.ProductCategoryMapCollection productsCatMap = null;

            productsCatMap = new ProductCategoryMapCollection().Where("CategoryID", SubSonic.Comparison.Equals, parentcatid).OrderByAsc("listOrder").Load();

            if (productsCatMap.Count > 0)
            {
                int lvl = level + 1;
                foreach (ProductCategoryMap c in productsCatMap)
                {
                    Product p = new Product(c.ProductID);

                    ListItem li = new ListItem();
                    li.Text = string.Format("<span class='{1}'>{0}</span>", p.ProductName, "CouponProduct");
                    li.Value = p.ProductID.ToString();
                    li.Attributes.Add("style", string.Format("margin-left:{0}px;",lvl*20));

                    if (selected.Exists(delegate(int i) { return i == Int32.Parse(li.Value); }) == true)
                    {
                        li.Selected = true;
                    }

                    productList.Add(li);
                }
            }
        }

        private void InitializeComponent()
        {
        }

        private void InitializeSelected( string couponCode )
        {
            Commerce.Promotions.Coupon coup = Commerce.Promotions.Coupon.GetCoupon(couponCode);
            thisCoupon = new Coupon("CouponCode", couponCode);

            Type coupType = coup.CouponType.CouponClassType;
            PropertyInfo[] pi = coupType.GetProperties();

            foreach (PropertyInfo info in pi)
            {
                if (info.Name != "CouponCode" && info.Name != "CouponType" &&
                    info.Name != "IsSingleUse" && info.Name != "UserId" &&
                    info.Name != "NumberOfUses" && info.Name != "ExpirationDate")
                {
                    umbraco.uicontrols.PropertyPanel proppan = new umbraco.uicontrols.PropertyPanel();

                    proppan.Text = info.Name;

                    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(info, true);

                    if (attrs.Length > 0)
                    {
                        Commerce.Promotions.SelectorType c = (Commerce.Promotions.SelectorType)attrs[0];

                        bool includeProducts = false;
                        List<int> selected = new List<int>();
                        XDocument doc = XDocument.Parse(thisCoupon.XmlData);

                        if (c.GetSelectorType() == "CouponTypeSelector")
                        {
                            RadioButtonList freeShippingType = new RadioButtonList();

                            freeShippingType.Text = ""; //info.GetValue(coup, null).ToString();
                            freeShippingType.ID = info.Name;
                            freeShippingType.CssClass = "guiInputText";
                            freeShippingType.RepeatDirection = RepeatDirection.Horizontal;
                            
                            string[] s = c.typeList.Split(',');
                            freeShippingType.Items.Add( new ListItem(s[0]) );
                            freeShippingType.Items.Add( new ListItem(s[1]) );

                            string t = string.Empty;
                            foreach( XElement element in doc.Descendants(info.Name) )
                            {
                                t = element.Value;
                            }

                            foreach (ListItem li in freeShippingType.Items)
                            {
                                if (t == li.Text)
                                {
                                    li.Selected = true;
                                    break;
                                }
                            }

                            proppan.Controls.Add(freeShippingType);
                        }
                        else if (c.multiSelect)
                        {
                            if (c.GetSelectorType() == "ProductPicker")
                            {
                                includeProducts = true;
                            }

                            foreach (XElement element in doc.Descendants(info.Name).Descendants("int"))
                            {
                                selected.Add(Int32.Parse(element.Value));
                            }

                            CheckBoxList chkList = new CheckBoxList();

                            chkList.Text = info.GetValue(coup, null).ToString();
                            chkList.ID = info.Name;
                            chkList.CssClass = "guiInputText";
                            chkList.RepeatColumns = 2;
                            chkList.RepeatDirection = RepeatDirection.Vertical;

                            List<ListItem> list = BindCategoryData(selected, includeProducts);

                            chkList.Items.AddRange(list.ToArray());

                            proppan.Controls.Add(chkList);
                        }
                        else if (c.GetSelectorType() == "ProductPicker" && c.multiSelect == false)
                        {
                            foreach (XElement element in doc.Descendants(info.Name))
                            {
                                selected.Add(Int32.Parse(element.Value));
                            }

                            RadioButtonList radioList = new RadioButtonList();

                            radioList.Text = info.GetValue(coup, null).ToString();
                            radioList.ID = info.Name;
                            radioList.CssClass = "guiInputText";
                            radioList.RepeatColumns = 2;
                            radioList.RepeatDirection = RepeatDirection.Vertical;

                            List<ListItem> list = BindCategoryData(selected, true);

                            radioList.Items.AddRange(list.ToArray());

                            proppan.Controls.Add(radioList);

                        }
                    }
                    else
                    {
                        //CheckBoxListIncludeCat.Visible = false;

                        TextBox txtValue = new TextBox();
                        txtValue.CssClass = "guiInputText";
                        txtValue.Width = 300;
                        txtValue.Text = info.GetValue(coup, null).ToString();
                        txtValue.ID = info.Name;

                        proppan.Controls.Add(txtValue);
                    }

                    Panel3.Controls.Add(proppan);

                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            string couponCode = Request.QueryString.Get("c");
            InitializeSelected(couponCode);

            //Add Save button
            ImageButton button = this.Panel1.Menu.NewImageButton();
            button.Click += new ImageClickEventHandler(this.save_click);
            button.AlternateText = "Save";
            button.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";
            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);
        }

        protected void OnDayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date.ToShortDateString() == ExpirationDate.ToShortDateString())
            {
                e.Cell.BackColor = System.Drawing.Color.Aqua;
            }
        }

        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveCoupon(base.Request.QueryString["c"]))
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "Coupon Saved"), "");
            }
            else
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "Error Saving Coupon"));
            }
        }

        private bool SaveCoupon(string couponCode)
        {
            try
            {
                Coupon thisCoupon = new Coupon("CouponCode",couponCode);

                thisCoupon.CouponCode = CouponCode.Text;
                if (CouponType.SelectedValue != "0")
                {
                    thisCoupon.CouponTypeId = int.Parse(CouponType.SelectedValue);
                }
                thisCoupon.IsSingleUse = IsSingleUse.Checked;
                thisCoupon.ExpirationDate = DateTime.Parse(ExpirationDate1.Text);

                Commerce.Promotions.Coupon temp = Commerce.Promotions.Coupon.GetCoupon(CouponCode.Text);

                object testing = Activator.CreateInstance(temp.CouponType.CouponClassType);

                Type test = temp.CouponType.CouponClassType;
                PropertyInfo[] pi = test.GetProperties();

                foreach (PropertyInfo info in pi)
                {
                    if (info.Name != "CouponCode" && info.Name != "CouponType" &&
                        info.Name != "IsSingleUse" && info.Name != "UserId" &&
                        info.Name != "NumberOfUses" && info.Name != "ExpirationDate")
                    {

                        if (Panel3.FindControl(info.Name) != null)
                        {
                            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(info,true);

                            if (attrs.Length > 0)
                            {
                                Commerce.Promotions.SelectorType c = (Commerce.Promotions.SelectorType)attrs[0];

                                if (c.GetSelectorType() == "CouponTypeSelector")
                                {
                                    RadioButtonList chkList = (RadioButtonList)Panel3.FindControl(info.Name);

                                    if (chkList.SelectedIndex != -1)
                                    {
                                        info.SetValue(temp, chkList.SelectedValue, null);
                                    }
                                    if (c.automatic == true && chkList.SelectedValue=="Yes")
                                    {
                                        thisCoupon.AutoAppliedCoupon = true;
                                    }
                                }
                                else if (c.multiSelect)
                                {
                                    CheckBoxList chkList = (CheckBoxList)Panel3.FindControl(info.Name);
                                    List<int> tmp = new List<int>();

                                    for (int i = 0; i < chkList.Items.Count; i++)
                                    {
                                        if (chkList.Items[i].Selected == true)
                                        {
                                            tmp.Add( Int32.Parse(chkList.Items[i].Value) );
                                        }
                                    }

                                    info.SetValue(temp, tmp, null);
                                }
                                else if (c.GetSelectorType() == "ProductPicker" && c.multiSelect == false)
                                {
                                    RadioButtonList chkList = (RadioButtonList)Panel3.FindControl(info.Name);

                                    if (chkList.SelectedIndex != -1)
                                    {
                                        int _tmp = Int32.Parse(chkList.SelectedValue);
                                        info.SetValue(temp, _tmp, null);
                                    }
                                }
                            }
                            else
                            {
                                TextBox value = (TextBox)Panel3.FindControl(info.Name);

                                info.SetValue(temp, Convert.ChangeType(value.Text, info.PropertyType), null);
                            }
                        }
                    }
                }             
               
                thisCoupon.XmlData = temp.GetXmlData();                
                thisCoupon.Save();

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
